import axios from "axios";
import { app } from "@/main";

export default {
  that() {
    return app.config.globalProperties;
  },
  get(url, data, success, s_tip, e_tip, loading, target, error) {
    let instance = loading && this.that().$loading({ text: "请稍后...", target: target});
    axios.get(url, data).then(res => {
      loading && instance.close();
      let resData = res.data || {};
      if (resData.code === "success") {
        // 如何 tip 是 bool 类型，就显示默认信息
        s_tip && this.that().$message.success(s_tip === true ? "操作成功" : s_tip);
        success && success(resData);
      } else if (resData.code === "login") {
        if (this.that().$route.name !== "login") {
          // 防止重复提示
          this.that().$router.replace({name: "login"});
          e_tip && this.that().$message.error(e_tip === true ? resData.msg : e_tip);
        }
      } else {
        // 如何 tip 是 bool 类型，就显示默认信息
        e_tip && this.that().$message.error(e_tip === true ? resData.msg : e_tip);
        error && error(resData);
      }
    }).catch(e => {
      loading && instance.close();
      this.that().$message.error(e);
    });
  },
  post(url, data, success, s_tip, e_tip, loading, target, error) {
    let instance = loading && this.that().$loading({ text: "请稍后...", target: target});
    axios.post(url, data).then(res => {
      loading && instance.close();
      let resData = res.data || {};
      if (resData.code === "success") {
        // 如何 tip 是 bool 类型，就显示默认信息
        s_tip && this.that().$message.success(s_tip === true ? "操作成功" : s_tip);
        success && success(resData);
      } else if (resData.code === "login") {
        if (this.that().$route.name !== "login") {
          // 防止重复提示
          this.that().$router.replace({name: "login"});
          e_tip && this.that().$message.error(e_tip === true ? resData.msg : e_tip);
        }
      } else {
        // 如何 tip 是 bool 类型，就显示默认信息
        e_tip && this.that().$message.error(e_tip === true ? resData.msg : e_tip);
        error && error(resData);
      }
    }).catch(e => {
      loading && instance.close();
      this.that().$message.error(e);
    });
  }
};